package com.zu.commu.auto1_0.protocol.waterLevel;

import com.zu.commu.auto1_0.DataType1_0;
import com.zu.commu.auto1_0.protocol.CheckData;
import com.zu.commu.auto1_0.protocol.Util;
import com.zu.commu.exception.CommuException;

public class WaterLevelProtocol {
    public byte[] remoteData(String meterNo, String value)
            throws Exception {
        String temp = "";
        try {
            temp = checkValue(value);
            temp = canonValue(temp);
        } catch (Exception e) {
            throw e;
        }
        byte[] buf = new byte[16];
        buf[0] = 104;
        buf[1] = 10;
        buf[2] = 10;
        buf[3] = 104;
        Util u = new Util();
        try {
            byte[] b = u.hex2Byte(meterNo);
            for (int i = 0; i < b.length; i++)
                buf[(4 + i)] = b[i];
        } catch (Exception e) {
            throw new CommuException().setMessage(
                    "测控器地址号不合法！" + e.getMessage(), null);
        }
        buf[10] = 64;
        buf[11] = (byte) DataType1_0.WATERLEVEL.toInt();
        try {
            byte[] b = u.hex2Byte(temp);
            for (int i = 0; i < b.length; i++)
                buf[(12 + i)] = b[i];
        } catch (Exception e) {
            throw new CommuException().setMessage("水位计量程数据不合法值！" + e.getMessage(),
                    e);
        }
        buf[14] = new CheckData().getCrcCheck(buf, 4, 13);
        buf[15] = 22;
        return buf;
    }

    public String checkValue(String value)
            throws CommuException {
        value = new Util().cleanDotNumber(value);
        if (value.equals("")) {
            throw new CommuException().setMessage("水位计量程数据不合法值！", null);
        }
        if (value.startsWith("-")) {
            throw new CommuException().setMessage("水位计量程数据不合法值！", null);
        }
        if (value.length() > 6) {
            throw new CommuException().setMessage("水位计量程数据超出合法值范围！", null);
        }
        int temp = 0;
        try {
            temp = Integer.parseInt(value);
        } catch (Exception e) {
            throw new CommuException().setMessage("水位计量程数据不合法值！", null);
        }
        if (temp > 656) {
            throw new CommuException().setMessage("水位计量程数据超出合法值范围！", null);
        }
        return temp + "";
    }

    public String canonValue(String value) {
        String temp = value;
        if (temp.length() < 4) {
            int n = 4 - temp.length();
            for (int i = 0; i < n; i++) {
                temp = "0" + temp;
            }
        }
        return temp;
    }
}